<?php

class User extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        
    }

    public function register()
    {
        if($this->input->server('REQUEST_METHOD') == 'POST')
        {
            $userinfo['email'] = trim($this->input->post('email'));
            $userinfo['passwd'] = trim($this->input->post('passwd'));
            $userinfo['passwd2'] = trim($this->input->post('passwd2'));

            $this->load->helper('email');
            
            $reg_error = array();
            if(empty($userinfo['email']))
            {
                $reg_error['mail'] = '请输入邮箱地址';
            }
            else
            {
                if(!valid_email($userinfo['email']))
                {
                    $reg_error['mail'] = '请输入合法的邮箱地址';
                }
                elseif($this->user_model->find_by_email($userinfo['email']))
                {
                    $reg_error['email'] = '邮箱地址已存在';
                }
            }

            if(empty($userinfo['passwd']))
            {
                $reg_error['passwd'] = '密码不能为空';
            }
            else
            {
                if($userinfo['passwd'] != $userinfo['passwd2'])
                {
                    $reg_error['passwd'] = '两次密码不一致';
                }
            }

            if(!count($reg_error))
            {
                unset($userinfo['passwd2']);
                if($this->user_model->add($userinfo))
                {
                    header('location:/user/sign_in');
                }
            }

            $this->tpl->assign('userinfo', $userinfo);
            $this->tpl->assign('reg_error', $reg_error);
        }
        
        $this->tpl->display('user_register.html');
    }

    public function login()
    {
        if($this->input->server('REQUEST_METHOD') == 'POST')
        {
            $email = trim($this->input->post('email'));
            $passwd = trim($this->input->post('passwd'));
            $remember = $this->input->post('remember');
            if($this->user_model->login($email, $passwd, $remember))
            {
                header('location:/');
            }
            $this->tpl->assign('login_error', '帐号或密码不正确');
        }

        $this->tpl->display('user_login.html');
    }

    public function logout()
    {
        $this->user_model->logout();
        header('location:/');
    }
}